package nckd.wnqjt.tmc.tda.plugin.form;

import com.alibaba.fastjson.JSON;
import kd.bos.ai.util.JsonUtil;
import kd.bos.algo.DataSet;
import kd.bos.algo.Row;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.entity.AppInfo;
import kd.bos.entity.AppMetadataCache;
import kd.bos.entity.qing.*;
import kd.bos.entity.report.ReportQueryParam;
import kd.bos.form.IFormView;
import kd.bos.form.IPageCache;
import kd.bos.form.ShowType;
import kd.bos.form.control.IQingAnalysis;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.ListShowParameter;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.mvc.SessionManager;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.report.ReportShowParameter;
import kd.bos.servicehelper.QueryServiceHelper;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhujintao
 * @date 2024/11/05
 * @desc 资金总额
 */
public class TotalfundsQingDataProvider extends AbstractFormPlugin implements IQingDataProvider {
    private static Log log = LogFactory.getLog(TotalfundsQingDataProvider.class);


    /**
     * 获取表头信息定义
     */
    @Override
    public QingMeta getMeta(String pageId) {
        String entityKey = "bei_bankbalance";
        QingMeta meta = new QingMeta();
        EntryEntity entity = new EntryEntity();
        entity.setKey(entityKey); //实体名(唯一标识)	是
        entity.setName(new LocaleString("余额查询")); //实体别名	是
        entity.setPkFieldName("id");//主键名称	是
        meta.addEntryEntity(entity);

        Field column = new Field();
        column.setEntity(entityKey);//字段所属实体key	否
        column.setKey("id");// 字段名(唯一标识)	是
        column.setFieldType(QingFieldType.Int.toNumber()); //数据类型	是
        column.setName(new LocaleString("id")); //字段别名	是
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("totalfunds");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("资金总额"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("restrictedfunds");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("受限资金"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("availablefunds");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("可用资金"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("bankenterprisebalance");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("银企余额"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("notbankenterprisebalance");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("非银企余额"));
        meta.addColumn(column);

        /*column = new Field();
        column.setEntity(entityKey);
        column.setKey("bizdate");
        column.setFieldType(QingFieldType.DateTime.toNumber());
        column.setName(new LocaleString("日期"));
        meta.addColumn(column);*/
        return meta;
    }

    /**
     * 获取轻分析数据
     *
     * @param startRow 起始行
     * @param limit    每页的数据量
     * @return 轻分析数据
     */
    @Override
    public QingData getData(String pageId, int startRow, int limit) {
        //拿过滤条件，进行取数
        String qFilter = getPageCache().get("qFilter");
        if (qFilter != null) {
            //通过此方法拿到过滤参数
            Map<String, Object> filterParam = (Map) JSON.parseObject(qFilter, Map.class);
        }
        //实体账户当前余额+受限资金管理中银行账户是虚拟户受限金额+定期存款管理中定期账户是虚拟户的投资理财
        /**
         * ***************************************************************
         */
        //子公司当前余额+母公司当前余额 排除结算中心
        QFilter finorgtype = new QFilter("number", QCP.equals, "FI-015");
        DynamicObject queryOne = QueryServiceHelper.queryOne("bd_finorgtype", "id", finorgtype.toArray());
        QFilter beiBankbalanceFilter = null;
        if (queryOne != null) {
            Object pkValue = queryOne.getLong("id");
            beiBankbalanceFilter = new QFilter("bank.finorgtype.id", QCP.not_equals, pkValue);
        }
        log.info("资金总额余额查询条件 " + beiBankbalanceFilter.toString());
        //QFilter beiBankbalanceFilter = new QFilter("bank.name", QCP.not_like, "结算中心");
        String beiBankbalanceSelectField = "id,company.id companyid,company.number companynumber,company.name companyname" +
                ",accountbank.id accountbankid,accountbank.bankaccountnumber bankaccountnumber,bizdate,nckd_depositbalance,amount,freezebalance,datasource";
        DataSet beiBankbalanceDataSet = QueryServiceHelper.queryDataSet(this.getClass().getName(), "bei_bankbalance", beiBankbalanceSelectField, beiBankbalanceFilter.toArray(), null);

        //日志打印
        StringBuffer beiBankbalanceDataSetlog = new StringBuffer();
        DataSet beiBankbalanceDataSetcopy = beiBankbalanceDataSet.copy();
        while (beiBankbalanceDataSetcopy.hasNext()) {
            Row next = beiBankbalanceDataSetcopy.next();
            beiBankbalanceDataSetlog.append(next.getString("bankaccountnumber")).append(" # ");
        }
        log.info("资金总额余额查询列表 " + beiBankbalanceDataSetlog);
        log.info("资金总额余额查询列表 " + beiBankbalanceDataSetlog.length());
        //取 账号维度的 最大日期的 当前余额
        DataSet beiBankbalanceGroupDataSet = beiBankbalanceDataSet.groupBy(new String[]{"companyid", "bankaccountnumber"})
                .maxP("bizdate", "freezebalance")
                .maxP("bizdate", "amount")
                .maxP("bizdate", "datasource")
                .finish();

        //日志打印
        StringBuffer beiBankbalanceGroupDataSetlog = new StringBuffer();
        DataSet beiBankbalanceGroupDataSetcopy = beiBankbalanceGroupDataSet.copy();
        while (beiBankbalanceGroupDataSetcopy.hasNext()) {
            Row next = beiBankbalanceGroupDataSetcopy.next();
            beiBankbalanceGroupDataSetlog.append(next.getString("bankaccountnumber")).append(" # ");
        }
        log.info("资金总额账户余额查询最大日期列表 " + beiBankbalanceGroupDataSetlog);
        log.info("资金总额账户余额查询最大日期列表 " + beiBankbalanceGroupDataSetlog.length());
        //获取符合条件的虚拟账户列表
        QFilter acctstatusfilter = new QFilter("acctstatus", QCP.not_equals, "closed").and("isvirtual", QCP.equals, true);
        String getAcctSelectedFieds = "id,company,openorg,issetbankinterface,bank,bankaccountnumber,isvirtual,name,currencyname,defaultcurrency,opendate,acctstatus,acctstyle,accttype,acctproperty,manager,acctname,finorgtype";
        DataSet acctDataSet = QueryServiceHelper.queryDataSet(this.getClass().getName(), "bd_accountbanks", getAcctSelectedFieds, acctstatusfilter.toArray(), null);
        List<String> isvirtualAccountNoList = new ArrayList<>();
        while (acctDataSet.hasNext()) {
            Row next = acctDataSet.next();
            String bankaccountnumber = next.getString("bankaccountnumber");
            isvirtualAccountNoList.add(bankaccountnumber);
        }
        //受限资金管理
        String amRestrictedfundsmanagerSelectField = "id,org.id companyid,org.number companynumber,org.name companyname,bankacct.id accountbankid,bankacct.bankaccountnumber bankaccountnumber,unrestrictedamt";
        //增加受限
        QFilter businesstype = new QFilter("businesstype", QCP.equals, "1").and("billstatus", QCP.equals, "C")
                .and("bankacct.bankaccountnumber", QCP.in, isvirtualAccountNoList);
        DataSet amRestrictedfundsmanagerDataSet = QueryServiceHelper.queryDataSet(this.getClass().getName(), "am_restrictedfundsmanager", amRestrictedfundsmanagerSelectField, businesstype.toArray(), null);

        //定期存款处理
        QFilter cimDepositQfilter = new QFilter("billstatus", QCP.equals, "C").and("finaccount", QCP.in, isvirtualAccountNoList);
        String cimDepositSelectField = "id,org.id companyid,org.number companynumber,org.name companyname,settleaccount.id accountbankid,settleaccount.bankaccountnumber bankaccountnumber,surplusamount";
        DataSet cimDepositDataSet = QueryServiceHelper.queryDataSet(this.getClass().getName(), "cim_deposit", cimDepositSelectField, cimDepositQfilter.toArray(), null);
        //最后 汇总 成资金总额 余额查询的全部当前余额 + 受限资金管理的全部虚拟户当前可解除受限金额  + 虚拟户定期存款处理的剩余金额
        DataSet amountSum = beiBankbalanceGroupDataSet.copy().groupBy().sum("amount").sum("freezebalance").finish();
        DataSet unrestrictedamtSum = amRestrictedfundsmanagerDataSet.groupBy().sum("unrestrictedamt").finish();
        DataSet surplusamountSum = cimDepositDataSet.groupBy().sum("surplusamount").finish();
        //过滤出来银企接口的数据用于统计
        DataSet frombankFilter = beiBankbalanceGroupDataSet.filter("datasource = 'frombank'").groupBy().sum("amount").finish();
        //资金总额
        List<BigDecimal> totalfunds = new ArrayList<>();
        //受限资金 = 余额查询的全部冻结余额 + 受限资金管理的全部虚拟户当前可解除受限金额  + 虚拟户定期存款处理的剩余金额
        List<BigDecimal> restrictedfunds = new ArrayList<>();
        while (amountSum.hasNext()) {
            Row next = amountSum.next();
            log.info("资金总额当前余额 " + next.getBigDecimal("amount"));
            totalfunds.add(next.getBigDecimal("amount"));
            log.info("资金总额冻结金额 " + next.getBigDecimal("freezebalance"));
            restrictedfunds.add(next.getBigDecimal("freezebalance"));
        }
        while (unrestrictedamtSum.hasNext()) {
            Row next = unrestrictedamtSum.next();
            log.info("资金总额受限金额 " + next.getBigDecimal("unrestrictedamt"));
            totalfunds.add(next.getBigDecimal("unrestrictedamt"));
            restrictedfunds.add(next.getBigDecimal("unrestrictedamt"));
        }
        while (surplusamountSum.hasNext()) {
            Row next = surplusamountSum.next();
            log.info("资金总额存款金额 " + next.getBigDecimal("surplusamount"));
            totalfunds.add(next.getBigDecimal("surplusamount"));
            restrictedfunds.add(next.getBigDecimal("surplusamount"));
        }
        //银企余额
        BigDecimal frombank = new BigDecimal(0);
        while (frombankFilter.hasNext()) {
            Row next = frombankFilter.next();
            log.info("资金总额银企余额 " + next.getBigDecimal("amount"));
            frombank = frombank.add(next.getBigDecimal("amount"));
        }
        //资金总额
        BigDecimal total = totalfunds.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
        //受限资金
        BigDecimal constrained = restrictedfunds.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
        //可用资金
        BigDecimal available = total.subtract(constrained);
        //非银企余额
        BigDecimal notfrombank = total.subtract(frombank);

        QingData data = null;
        if (startRow < 200) {
            data = new QingData();
            Map<String, Integer> dataindex = new HashMap<String, Integer>();
            dataindex.put("id", 0);
            dataindex.put("totalfunds", 1);
            dataindex.put("restrictedfunds", 2);
            dataindex.put("availablefunds", 3);
            dataindex.put("bankenterprisebalance", 4);
            dataindex.put("notbankenterprisebalance", 5);
            data.setDataindex(dataindex);

            List<Object[]> rows = new ArrayList<Object[]>();
            Object[] obj = new Object[6];
            obj[0] = 999999;
            obj[1] = total;
            obj[2] = constrained;
            obj[3] = available;
            obj[4] = frombank;
            obj[5] = notfrombank;
            rows.add(obj);
            data.setRows(rows);
        }
        return data;
    }


    @Override
    public void setFilterParameter(String filterParameter) {
        IPageCache pageCache = getPageCache();
        pageCache.put("qFilter", filterParameter);

    }

    @Override
    public String getFilterParameter() {
        return getPageCache().get("qFilter");
    }

    /**
     * 获取动态表单联查信息
     *
     * @param pageId
     * @param ctrKey
     * @return
     */
    @Override
    public List<QingLinkageInfo> getLinkageInfo(String pageId, String ctrKey) {
        //return IQingDataProvider.super.getLinkageInfo(pageId, ctrKey);
        List<QingLinkageInfo> infos = new ArrayList<QingLinkageInfo>();
        QingLinkageInfo info = new QingLinkageInfo();
        Map<String, String> formKey = new HashMap<>();
        AppInfo appInfo = AppMetadataCache.getAppInfo("bei");
        //String appId = this.getView().getFormShowParameter().getAppId();
        formKey.put("AppId", appInfo.getAppId()); //需要打开的表单所在应用的id
        //String formId = this.getView().getFormShowParameter().getFormId();
        formKey.put("FormId", "nckd_totalfundsrpt"); //需要打开的表单的id
        formKey.put("System", "IERP");
        formKey.put("CtrKey", ctrKey);
        info.setFormKey(JsonUtil.encodeToString(formKey));
        info.setFormDisplayName("资金明细报表");//联查到表单的显示名称
        info.setFormPrimaryKey("id");//联查到表单的主键
        infos.add(info);//可以添加多个QingLinkageInfo对象
        this.getView().getPageCache().put("qingViewControlKey", ctrKey);//必要语句!
        return infos;
    }

    /**
     * <p>调用此接口，触发业务逻辑，具体业务联查实现此接口<p/>
     *
     * @param ids    轻分析得到动态表单需要联査的1d的集合
     * @param pageId
     * @param formId
     * @param appId
     */
    @Override
    public void fireLinkageInfo(List<String> ids, String pageId, String formId, String appId) {
        //IQingDataProvider.super.fireLinkageInfo(ids, pageId, formId, appId);
        /*具体的表单打开逻辑，业务自己去实现
        ids:联查到的主键的值
        pageId:触发联査的页面的pageId，可用于找到触发联査的页面: FormView view = (FormView)Sessiomanager.getCurrent().getView(pageId)
        formId:联查到的表单的id
        appId:联查到的表单所在应用的Id
        */

        /*注意: 如果需要使用芒穹的view.showForm 方式打开表单，需要添加以下代码*/
        // 组装 FormShomParaneter(披照业务场景亲实现)
        ReportShowParameter reportShowParameter = new ReportShowParameter();
        reportShowParameter.getOpenStyle().setShowType(ShowType.Modal);
        reportShowParameter.setAppId(appId);
        reportShowParameter.setFormId(formId);//报表标识
        //拿过滤条件，进行取数
        String qFilter = getPageCache().get("qFilter"); //从仪表板进去 拿不到
        //通过此方法拿到过滤参数
        Map<String, Object> filterParam = new HashMap<>();
        // 设置报表过滤条件
        ReportQueryParam reportQueryParam = new ReportQueryParam();
        //FilterInfo filterInfo = new FilterInfo();
        //filterInfo.addFilterItem("nckd_orgview", filterParam.get("nckd_orgview"));
        //filterInfo.addFilterItem("nckd_org", filterParam.get("nckd_org"));
        //filterInfo.addFilterItem("nckd_currency", filterParam.get("nckd_currency"));
        //filterInfo.addFilterItem("bizdate", filterParam.get("nckd_querydate"));
        //filterInfo.addFilterItem("nckd_amountunit", filterParam.get("nckd_amountunit"));
        filterParam.put("id", ids);
        //reportQueryParam.setFilter(filterInfo);
        reportQueryParam.setCustomParam(filterParam);
        reportShowParameter.setQueryParam(reportQueryParam);

        /*******************************showForm必要的代码******************************************/
        IFormView view = SessionManager.getCurrent().getView(pageId);
        String ctrKey = this.getView().getPageCache().get("qingViewControlKey");
        if (ctrKey != null) {
            if (view.getControl(ctrKey) instanceof IQingAnalysis) {
                //设计器的场景，直接showForm
                view.showForm(reportShowParameter);
                return;
            }
        }
        //其他场景需要，返回FormShowParameter，由轻分析来 showForm
        this.getView().setClientReturnData(ListShowParameter.toJsonString(reportShowParameter));
        /*******************************showForm必要的代码******************************************/
    }
}